package com.yc.fruitmarket.biz.impl;

import java.util.List;
import java.util.Map;

import com.yc.fruitmarket.biz.cartBiz;
import com.yc.fruitmarket.dao.DBHelper;

public class cartBizImpl implements cartBiz {
	private DBHelper db = new DBHelper();
	public int getCartCount(String uid) {
		String sql = "select count(cid) as count from cart where uid = ?";
		List<Map<String, String>> list = db.find(sql, uid);
		return Integer.parseInt(list.get(0).get("count"));
	}
	@Override
	public int addCart(String uid, String pid, String num,String inventory) {
		String sql = "select * from cart where pid = ?";
		List<Map<String, String>> list = db.find(sql, pid);
		if(db.find(sql, pid).size() > 0) {
			//有则修改数量
			if(Integer.parseInt(list.get(0).get("cartnum")) + Integer.parseInt(num) <= Integer.parseInt(inventory)) {
				sql = "update cart set cartnum = cartnum + ? where pid = ?";
				db.doUpdate(sql,num, pid);
				return 1;
			}else {
				return 3;
			}
			
		}else {
			if(Integer.parseInt(num) <= Integer.parseInt(inventory)) {
				sql = "insert into cart values(null,?,?,?,1)";
				db.doUpdate(sql, uid,pid,num);
				return 2;
			}else {
				return 3;
			}
			
		}
	}
	@Override
	public List<Map<String, String>> getCartsByUid(String uid) {
		String sql = "select * from product,cart where product.pid = cart.pid and cart.uid = ? and cart.status = 1";
		return db.find(sql, uid);
	}
	@Override
	public int changeNum(String cid, String cartnum, String inventory) {
		if(Integer.parseInt(cartnum) <= Integer.parseInt(inventory)) {
			String sql = "update cart set cartnum = ? where cid = ?";
			return db.doUpdate(sql, cartnum, cid);
		}else {
			return -1;
		}
	}
	@Override
	public int deleteCart(String cid) {
		String sql = "delete from cart where cid = ?";
		int result = db.doUpdate(sql, cid);
		return result;
	}
	@Override
	public List<Map<String, String>> findByCids(String cids) {
		String sql = "select * from cart, product where cart.pid = product.pid and cart.cid in ("+ cids +")";
		return db.find(sql);
	}
	//购买成功，删除购物车
	@Override
	public int deleteCartP(String uid, String cids) {
		String sql = "DELETE from cart where uid = ? and cid in ("+ cids +")";
		return db.doUpdate(sql, uid);
	}
}
